package com.hxzy.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.dto.CreateOrderDTO;
import com.hxzy.entity.AddressBook;
import com.hxzy.entity.OrderDetail;
import com.hxzy.entity.Orders;
import com.hxzy.entity.ShoppingCart;
import com.hxzy.mapper.OrdersMapper;
import com.hxzy.service.AddressBookService;
import com.hxzy.service.OrderDetailService;
import com.hxzy.service.OrdersService;
import com.hxzy.service.ShoppingCartService;
import com.hxzy.vo.LoginVO;
import com.hxzy.vo.OrdersVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单
 * @author Administrator
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询当年交易额
     * @return
     */
    @Override
    public long fullYearTotalMoney() {
        Long merchantId=null;
        if(!WaimaiThreadLocal.isSuperMan()){
            merchantId=WaimaiThreadLocal.getCurrent().getAccountVO().getId();
        }

        return this.getBaseMapper().fullYearTotalMoney(merchantId);
    }

    /**
     * 查询当前年的呢的交易笔数
     * @return
     */
    @Override
    public long fullYearTotalOrders() {
        Long merchantId=null;
        if(!WaimaiThreadLocal.isSuperMan()){
            merchantId=WaimaiThreadLocal.getCurrent().getAccountVO().getId();
        }

        return this.getBaseMapper().fullYearTotalOrders(merchantId);
    }

    /**
     * 未完成的订单数
     * @return
     */
    @Override
    public long outstandingOrders() {
        Long merchantId=null;
        if(!WaimaiThreadLocal.isSuperMan()){
            merchantId=WaimaiThreadLocal.getCurrent().getAccountVO().getId();
        }
        return this.getBaseMapper().outstandingOrders(merchantId);
    }

    /**
     * 查询用户最近一笔订单信息
     * @return
     */
    @Override
    public OrdersVO lastOrder() {
        LoginVO loginVO=WaimaiThreadLocal.getCurrent();
        OrdersVO ordersVO= this.getBaseMapper().lastOrder(loginVO.getAccountVO().getId());
        return ordersVO;
    }

    /**
     * 创建订单
     * @param createOrderDTO
     * @return 订单ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String createOrder(CreateOrderDTO createOrderDTO) {
        LoginVO loginVO=WaimaiThreadLocal.getCurrent();

        Orders order=new Orders();
        order.setMerchantId(createOrderDTO.getMerchantId());
        order.setAddressBookId(createOrderDTO.getAddressBookId());
        order.setStatus(1);
        order.setUserId(loginVO.getAccountVO().getId());
        order.setNumber(IdUtil.getSnowflakeNextIdStr());
        order.setOrderTime(new Date());
        order.setRemark(createOrderDTO.getRemark());

        //查询到收货人信息
        AddressBook addressBook = this.addressBookService.getById(createOrderDTO.getAddressBookId());
       order.setConsignee(addressBook.getConsignee());
       order.setPhone(addressBook.getPhone());
       order.setUserName(loginVO.getAccountVO().getName());

       String address= StrUtil.format("{}{}{}{}",addressBook.getProvinceName(),
               addressBook.getCityName(),addressBook.getDistrictName(),addressBook.getDetail());
        order.setAddress(address);

        //查询购物车的明细
        List<ShoppingCart> shoppingCartList = this.shoppingCartService.findUserCartByMerchandId(createOrderDTO.getMerchantId());

        //汇总金额(实收金额)
        double amount=shoppingCartList.stream().mapToDouble( p->  p.getAmount().doubleValue()).sum();
        order.setAmount(new BigDecimal(amount));

        //保存订单信息
        boolean save = this.save(order);
        if(save){
            //写入订单明细
            for (ShoppingCart  shoppingCart: shoppingCartList) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(order.getId());
                orderDetail.setAmount(shoppingCart.getAmount());
                orderDetail.setMerchantId(shoppingCart.getMerchantId());
                orderDetail.setNumber(shoppingCart.getNumber());
                orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
                orderDetail.setDishId(shoppingCart.getDishId());
                orderDetail.setName(shoppingCart.getName());
                orderDetail.setImage(shoppingCart.getImage());
                save=this.orderDetailService.save(orderDetail);
            }

            //删除购物车的信息
            this.shoppingCartService.clean(createOrderDTO.getMerchantId());
        }

        return order.getNumber();
    }

    @Override
    public Orders findByOrderNumber(String orderNumber) {
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("number",orderNumber);
        return this.getOne(queryWrapper);
    }

    /**
     * 更新订单表的状态
     * @param orderNumber
     * @param payTime
     * @param buyerAmount
     * @return
     */
    @Override
    public int updatePayStatusByOrderId(String orderNumber, String payTime,String buyerAmount) {
       return  this.getBaseMapper().updateAliPayPayStatus(orderNumber,payTime,buyerAmount);

    }
}
